<template>
    <div class='page-container'>
        <header class="tab-row">
            <span class="tab active">{{title}}</span>
            <span class="tab" v-if='title === "服务人员详情"' @click='serverOrder'>服务人员订单</span>
        </header>
        <div class="page-content">
            <el-button class="back-btn" icon='el-icon-arrow-left' type='plain' @click='$router.back()'>返回</el-button>
            <div>
                <el-form :model="vmData" :rules="rules" ref="form" label-width="100px" label-position="left">
                    <form-chunk-label v-if="isAdd" title="所属机构"></form-chunk-label>
                    <el-row class="info-container" v-if="isAdd">
                        <el-form-item label="服务区域" prop="area">
                            <el-select v-model="vmData.area">
                                <el-option v-for="area in dics.serviceAreas"
                                        :key="area.id"
                                        :label="area.name"
                                        :value="area"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-row>
                    <form-chunk-label title="基本信息" id='initInfo'>
                        <el-button v-if="!isEdit && !isGover"
                                icon="el-icon-edit"
                                type="primary"
                                size="small"
                                @click="$router.push(`/integratedMana/worker/${$route.params.id}/edit`)">
                            修改
                        </el-button>
                        <el-button @click='map' size="small" type="primary" icon='el-icon-location-outline'>地图定位</el-button>
                        <span style='margin-left: 10px;'>红色代表：签到忙碌，绿色代表：签退空闲</span>
                    </form-chunk-label>
                    <el-row class="info-container">
                        <el-row>
                            <el-col :span="10">
                                <el-form-item label="职位" prop="post" style='position: relative;'>
                                    <el-select v-model="vmData.post" :disabled="!isEdit">
                                        <el-option v-for="item in post"
                                                :key="item.id"
                                                :label="item.text"
                                                :value="item.id">
                                        </el-option>
                                    </el-select>
                                    <el-rate disabled v-model='vmData.startRating' style='position: absolute; right: 0; top: 50%; transform: translate3d(0, -50%, 0)'></el-rate>
                                </el-form-item>
                                <el-form-item label="姓名" prop="name">
                                    <el-input v-model="vmData.name" :disabled="hasMoreRole"></el-input>
                                </el-form-item>
                                <el-form-item label="性别" prop="sex">
                                    <el-select v-model="vmData.sex" :disabled="hasMoreRole">
                                        <el-option label="男" :value="1"></el-option>
                                        <el-option label="女" :value="2"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="身份证号" prop="idNo" label-position="top">
                                    <el-input v-model="vmData.idNo" :disabled="hasMoreRole"></el-input>
                                </el-form-item>
                                <el-form-item label="出生年月" prop="birthday">
                                    <el-input v-model="vmData.birthday" disabled></el-input>
                                </el-form-item>
                                <el-form-item label="民族" prop="nation">
                                    <el-select v-model="vmData.nation" :disabled="!isEdit">
                                        <el-option v-for="(item,$index) in dics.nations"
                                                :key="$index"
                                                :label="item"
                                                :value="$index+1">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="学历" prop="education">
                                    <el-select v-model="vmData.education" :disabled="!isEdit">
                                        <el-option
                                                v-for="item in dics.educations"
                                                :key="item.code"
                                                :label="item.desc"
                                                :value="item.code">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="毕业院校" prop="school">
                                    <el-input v-model="vmData.school" :disabled="!isEdit"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :offset="1" :span="10">
                                <el-form-item label="身高" prop="height">
                                    <el-input v-model="vmData.height" :disabled="!isEdit">
                                        <template slot="append">cm</template>
                                    </el-input>
                                </el-form-item>
                                <el-form-item label="体重" prop="weight">
                                    <el-input v-model="vmData.weight" :disabled="!isEdit">
                                        <template slot="append">kg</template>
                                    </el-input>
                                </el-form-item>
                                <el-form-item label="健康状况" prop="health">
                                    <el-input v-model="vmData.health" :disabled="!isEdit"></el-input>
                                </el-form-item>
                                <el-form-item label="婚姻状况" prop="maritalStatus">
                                    <el-input v-model="vmData.maritalStatus" :disabled="!isEdit"></el-input>
                                </el-form-item>
                                <el-form-item label="爱好" prop="hobbies">
                                    <el-input v-model="vmData.hobbies" :disabled="!isEdit"></el-input>
                                </el-form-item>
                                <el-form-item label="手机号" prop="mobile">
                                    <el-input v-model="vmData.mobile" :disabled="!isEdit"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-row v-for="(person,index) in vmData.familyRelationList"
                                    :key="index"
                                    type="flex"
                                    align="top"
                                    :gutter="10">
                                <el-form-item :label="`紧急联系人${index+1}`" required>
                                    <el-col :span="7">
                                        <el-form-item :prop="`familyRelationList.${index}.name`"
                                                    :rules="{required:true,message:'请输入联系人姓名'}">
                                            <el-input v-model="person.name" :disabled="!isEdit" placeholder="姓名"></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="7">
                                        <el-form-item :prop="`familyRelationList.${index}.relation`"
                                                    :rules="{required:true,message:'请输入与服务人员关系'}">
                                            <el-input v-model="person.relation"
                                                    :disabled="!isEdit"
                                                    placeholder="与服务人员关系"></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="7">
                                        <el-form-item :prop="`familyRelationList.${index}.mobile`"
                                                    :rules="rules.mobile">
                                            <el-input v-model.number="person.mobile"
                                                    :disabled="!isEdit"
                                                    placeholder="手机号码"></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="3" v-if="isEdit && index > 0">
                                        <el-button type="plain" icon="delete" @click="delContactPerson(index)"></el-button>
                                    </el-col>
                                </el-form-item>
                            </el-row>
                            <el-form-item label-width="0" v-if="isEdit">
                                <el-button v-if="isEdit"
                                        @click="addContactPerson"
                                        type="primary"
                                        size="small">添加紧急联系人
                                </el-button>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-form-item label="居住地址">
                                <el-row :gutter="10" type="flex" justify="between">
                                    <template v-if="isAdd">
                                        <el-col :span="8">
                                            <el-form-item prop="provinceTmp">
                                                <el-select v-model="vmData.provinceTmp"
                                                        placeholder="省"
                                                        @change="cascadeSelect('getCityByPid','cities',$event)">
                                                    <el-option v-for="({id,name}) in provinces"
                                                            :key="id"
                                                            :label="name"
                                                            :value="id">
                                                    </el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="8">
                                            <el-form-item prop="cityTmp">
                                                <el-select v-model="vmData.cityTmp"
                                                        placeholder="市"
                                                        :loading="pendingFlags.cities"
                                                        @change="cascadeSelect('getCityByPid','districts',$event)">
                                                    <el-option v-for="({id,name}) in dics.cities"
                                                            :key="id"
                                                            :label="name"
                                                            :value="id">
                                                    </el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="8">
                                            <el-form-item prop="districtTmp">
                                                <el-select v-model="vmData.districtTmp"
                                                        placeholder="区"
                                                        :loading="pendingFlags.districts">
                                                    <el-option v-for="({id,name}) in dics.districts"
                                                            :key="id"
                                                            :label="name"
                                                            :value="id">
                                                    </el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                    </template>

                                    <el-col>
                                        <el-form-item prop="address">
                                            <el-input v-model="vmData.address"
                                                    placeholder="居住地址"
                                                    :disabled="!isEdit"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-form-item label="账户余额" prop="money">
                                {{ tWorkerPositionVo.variableAmount || 0 }}元
                                <el-button style='margin-left: 20px;' type='primary' @click='total' v-if='!isGover' :disabled='!tWorkerPositionVo.variableAmount'>结算</el-button>
                            </el-form-item>
                            <div class="list">
                                <el-table :data="tableData" stripe border class="list"
                                        v-loading="pending"
                                        element-loading-text="正在请求数据...">
                                    <el-table-column 
                                        prop="operatingTime" 
                                        label="时间"
                                        align="center"
                                        >
                                    </el-table-column>
                                    <el-table-column
                                            prop="operatingName"
                                            label="操作账户名称"
                                            align="center">
                                    </el-table-column>
                                    <el-table-column
                                            prop="settlementAmount"
                                            label="结算金额"
                                            align="center"
                                            >
                                    </el-table-column>
                                </el-table>
                                <!--分页-->
                                <el-row type="flex" justify="center">
                                    <el-pagination @current-change="pageChange"
                                                :page-size="10"
                                                layout="total, prev, pager, next"
                                                :total="totleNum">
                                    </el-pagination>
                                </el-row>
                            </div>
                        </el-row>
                    </el-row>
                    <form-chunk-label title="相关证件"></form-chunk-label>
                    <el-row class="info-container">
                        <el-row v-for="(typeName,index) in ['身份证照片','健康证照片','学历照片','从业资格照片','其他证件照片']" :key="index">
                            <h5 class="picture-label">{{typeName}}</h5>
                            <el-form-item label-width="0" class="picture-list">
                                <el-upload action="http://upload.17link.cc/upload.do"
                                        :data="{type:index+1}"
                                        :on-success="uploadPic.bind(null,index+1)"
                                        :on-remove="removePic"
                                        :disabled="!isEdit"
                                        :file-list="getFileListByType(index+1)"
                                        list-type="picture-card">
                                    <i class="el-icon-plus"></i>
                                </el-upload>
                            </el-form-item>
                        </el-row>
                    </el-row>
                    <form-chunk-label title="服务内容"></form-chunk-label>
                    <el-row class="info-container">
                        <el-form-item label="服务大类" prop="cateList">
                            <el-checkbox-group v-model="vmData.cateList">
                                <el-checkbox :disabled="!isEdit" v-for="({cateId,cateName}) in dics.cates"
                                            :key="cateId"
                                            :label="cateId">{{cateName}}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-row>
                    <el-row class="info-container" type="flex" justify="end" align="middle" v-if="isEdit">
                        <el-button type="primary" @click="save(false)">保存</el-button>
                        <el-button v-if="isAdd" type="plain" @click="save(true)">保存录下一条</el-button>
                    </el-row>
                </el-form>
                <template v-if="!isEdit">
                    <form-chunk-label title="所属机构"></form-chunk-label>
                    <el-row class="info-container">
                        <el-form inline>
                            <el-form-item label="所属机构">
                                {{ vmData.orgName }}
                            </el-form-item>
                            <el-form-item label="所属服务区域">
                                <span>{{displayServiceArea}}</span>
                            </el-form-item>
                        </el-form>
                    </el-row>
                    <form-chunk-label title="培训考核情况">
                        <el-button v-if="isPf" icon="plus" size="small" type="primary" @click="trainFormVisible=true">添加考核</el-button>
                    </form-chunk-label>
                    <el-row class="info-container">
                        <el-table :data="trainList"
                                border
                                class="mt20px width100">
                            <el-table-column prop="post"
                                            label="项目"
                                            :formatter="trans4display"
                                            width="130">
                            </el-table-column>
                            <el-table-column prop="basicKnowledgeScore"
                                            label="基础知识成绩"
                                            width="80">
                            </el-table-column>
                            <el-table-column prop="workSkillScore"
                                            label="工作技能成绩"
                                            width="80">
                            </el-table-column>
                            <el-table-column prop="practicalOperationScore"
                                            label="实际操作成绩"
                                            width="80">
                            </el-table-column>
                            <el-table-column prop="trainingAssessmentTime"
                                            label="培训考核时间"
                                            :formatter="trans4display">
                            </el-table-column>
                            <el-table-column prop="createTime"
                                            label="录入时间"
                                            :formatter="trans4display">
                            </el-table-column>
                            <el-table-column label="操作"  v-if="isPf">
                                <template slot-scope="scope">
                                    <el-button size="small"
                                            @click="editTrain(scope.row)">修改
                                    </el-button>
                                    <el-button size="small"
                                            type="danger"
                                            @click="deleteTrain(scope.row.id)">删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-row>
                </template>
                <el-dialog title="培训成绩"
                        :visible.sync="trainFormVisible"
                        :close-on-click-modal="false"
                        :close-on-press-escape="false"
                        :show-close="false">
                    <el-form ref="trainForm" :model="trainForm" label-position="left" label-width="100px">
                        <el-form-item label="项目" prop="post">
                            <el-select v-model="trainForm.post" :disabled="trainForm.id>0">
                                <el-option v-for="({id,text}) in post"
                                        :key="id"
                                        :label="text"
                                        :value="id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="基础知识成绩" prop="basicKnowledgeScore">
                            <el-input-number v-model="trainForm.basicKnowledgeScore"
                                            :min="0"
                                            :max="100"
                                            :step="5"></el-input-number>
                        </el-form-item>
                        <el-form-item label="工作技能成绩" prop="workSkillScore">
                            <el-input-number v-model="trainForm.workSkillScore"
                                            :min="0"
                                            :max="100"
                                            :step="5">
                            </el-input-number>
                        </el-form-item>
                        <el-form-item label="实际操作成绩" prop="practicalOperationScore">
                            <el-input-number v-model="trainForm.practicalOperationScore"
                                            :min="0"
                                            :max="100"
                                            :step="5">
                            </el-input-number>
                        </el-form-item>
                        <el-form-item label="培训考核时间" prop="trainingAssessmentTime">
                            <el-date-picker v-model="trainForm.trainingAssessmentTime"
                                            type="date"
                                            :clearable="false"
                                            placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="resetTrainForm">取 消</el-button>
                        <el-button type="primary" @click="addTrain">确 定</el-button>
                    </div>
                </el-dialog>
            </div>
            <div v-if='mapFlag' id='allmap' class="map"></div>
        </div>
    </div>
</template>

<script>
  import { mapState, mapGetters, mapMutations } from 'vuex';
  import { cscService, umsService } from '../../../service.js';
  import FormChunkLabel from '@/components/FormChunkLabel.vue';
  import { format } from 'date-fns';
  import cloneDeep from 'lodash.clonedeep'
  import { required, isMobile } from '../../../CommonRules'
  import { UMS, MP } from '@/common/config'

  export default {
    data() {
      const validate = (rule, value, cb) => {
        if (/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value)) {
            cb();
        } else {
            cb(new Error('请输入正确的身份证号码'));
        }
      }
      return {
        dics: {
          serviceAreas: [],//服务区域数据源
          nations: [
            "汉族",
            "蒙古族",
            "回族",
            "藏族",
            "维吾尔族",
            "苗族",
            "彝族",
            "壮族",
            "布依族",
            "朝鲜族",
            "满族",
            "侗族",
            "瑶族",
            "白族",
            "土家族",
            "哈尼族",
            "哈萨克族",
            "傣族",
            "黎族",
            "僳僳族",
            "佤族",
            "畲族",
            "高山族",
            "拉祜族",
            "水族",
            "东乡族",
            "纳西族",
            "景颇族",
            "柯尔克孜族",
            "土族",
            "达斡尔族",
            "仫佬族",
            "羌族",
            "布朗族",
            "撒拉族",
            "毛南族",
            "仡佬族",
            "锡伯族",
            "阿昌族",
            "普米族",
            "塔吉克族",
            "怒族",
            "乌孜别克族",
            "俄罗斯族",
            "鄂温克族",
            "德昂族",
            "保安族",
            "裕固族",
            "京族",
            "塔塔尔族",
            "独龙族",
            "鄂伦春族",
            "赫哲族",
            "门巴族",
            "珞巴族",
            "基诺族"
          ],//民族数据源
          educations: [
            { code: 1, "desc": "小学" },
            { code: 2, "desc": "初中" },
            { code: 3, "desc": "中专" },
            { code: 4, "desc": "高中" },
            { code: 5, "desc": "专科" },
            { code: 6, "desc": "本科" },
            { code: 7, "desc": "硕士研究生" },
            { code: 8, "desc": "博士研究生" },
          ],//学历数据源
          cates: [],
          cities: [],
          districts: [],
        },
        vmData: {
          id: 0,
          orgID: 0,
          orgName: '',//D机构名称
          post: null,
          name: '',//姓名
          sex: null,//性别
          idNo: '',//身份证号
          nation: null,//名族
          education: null,//学历
          school: '',//学校
          height: '',//身高
          weight: '',//体重
          health: '',//健康状况
          maritalStatus: '',//婚姻状况
          hobbies: '',//爱好
          birthday: '',//生日
          mobile: null,//手机
          provinceId: null,//省份 ID
          cityId: null,//城市 ID
          districtId: null,//区 ID
          streetId: null,
          provinceTmp: null,
          cityTmp: null,
          districtTmp: null,
          startRating: 0,
          address: '',//居住地址
          familyRelationList: [
            {
              name: '',
              relation: '',
              mobile: null
            }
          ],
          picList: [],
          cateList: [],
          area: null,
        },
        sourceVM: {},
        trainList: [],
        trainFormVisible: false,
        trainForm: {
          id: 0,
          workerId: 0,
          post: null,
          basicKnowledgeScore: 0,
          workSkillScore: 0,
          practicalOperationScore: 0,
          trainingAssessmentTime: null,
        },
        displayServiceArea: '',
        pendingFlags: {
          cities: false,
          districts: false,
        },
        rules: {
          name: required('姓名'),
          post: required('职位'),
          height: required('身高'),
          weight: required('体重'),
          sex: required('性别'),
          health: required('健康情况'),
          idNo: {validator: validate, trigger: 'blur'},
          education: required('学历'),//学历
          school: required('学校'),//学校
          maritalStatus: required('婚姻状况'),//婚姻状况
          hobbies: required('爱好'),//爱好
          mobile: isMobile('手机'),//手机
          provinceId: required('省份'),//省份 ID
          cityId: required('城市'),//城市 ID
          districtId: required('区域'),//区 ID
          streetId: required('街道'),
          address: required('居住地址'),//居住地址
          nation: required('民族'),//居住地址
          cateList: { type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' },
          area: {
            type: 'object', required: true, message: '请选择服务区域'
          },
          provinceTmp: required('省份'),
          cityTmp: required('城市'),
          districtTmp: required('区'),
        },
        mapFlag: false,
        userInfo: window._dataInfo,
        tWorkerPositionVo: {},
        tableData: [],
        pending: false,
        totleNum: 0
      }
    },
    async created() {
      if (!this.provinces.length) {
          this.$http.get(`${UMS}/city/getAllProvince.do`).then(res => {
              if (res.data.errCode === 0) {
                  this.SET_Provinces(res.data.data.list)
              }
          })
      }
      const workerId = Number(this.$route.params.id);

      const { list: cates } = await cscService.getServiceCates();
      this.dics.cates = cates.map(({ cateName, catePid: cateId }) => ({ cateId, cateName }));
      if (this.isOrg && this.isAdd) {
        // 机构用户拉取当前机构服务区域信息
        const { list: areas } = await cscService.getServiceAreaByCompId(this.userInfo.orgId);
        this.dics.serviceAreas = areas.map(({ provinceId, streetId, cityId, zoneId, provinceName, streetName, cityName, zoneName }) =>
          ({
            name: provinceName + cityName  + zoneName  + streetName ,
            provinceId,
            streetId,
            cityId,
            zoneId,
          }));
      }
      this.trainForm.workerId = workerId;
      if (!this.isAdd) {
        this._getInit()
      }

      this.currentPage = 1
      this._getList()
    },
    beforeRouteLeave({ name: toName, query: { isFresh } }, { name: fromName }, next) {
      if (toName === 'WorkerDetail' && fromName === 'WorkerAdd' && !isFresh) {
        this.vmData = this.sourceVM;
        this.sourceVM = null;
      }
      if (toName === 'WorkerAdd' && fromName === 'WorkerDetail') {
        this.sourceVM = cloneDeep(this.vmData);
      }
      next()
    },
    methods: {
      _getList () {
        this.pending = true
          // 分页结算日志
        this.$http.get(`${MP}/settlement/queryAll?workerId=${this.trainForm.workerId}&currentPage=${this.currentPage}`).then(res => {
            this.pending = false
            let data = res.data
            if (!data.errCode) {
                this.totleNum = data.data.totalPageNum
                this.currentPage = data.data.currentPage
                this.tableData = data.data.settlementInfoList.filter(item => {
                    item.operatingTime = format(item.operatingTime, 'YYYY年MM月DD日 HH:mm')
                    return item.operatingType === 2
                })
            }
        })
      },
      /**
       * 增加一位紧急联系人信息
       */
      addContactPerson() {
        this.vmData.familyRelationList.push({
          name: '',
          relation: '',
          mobile: null,
        });
      },
      delContactPerson(index){
        this.vmData.familyRelationList = this.vmData.familyRelationList.filter((p, i) => i !== index);
      },
      uploadPic(type, { errCode, errMessage, data: { url } }) {
        if (errCode > 0) {
          alert(errMessage);
        }
        this.vmData.picList.push({
          picUrl: url,
          type
        });
      },
      removePic({ url }) {
        this.vmData.picList = this.vmData.picList.filter(p => p.picUrl !== url);
      },
      /**
       *
       * @param isResetAndContinue 是否清空表单继续填写服务人员信息
       * @return {Promise.<void>}
       */
      save(isResetAndContinue) {
        //提交
        this.$refs.form.validate(async valid => {
          if (valid) {
            try {
              if (this.submitData.worker.id) {
                await cscService.updateWorker(this.submitData);
              } else {
                await cscService.saveWorker(this.submitData);
              }
              if (isResetAndContinue) {
                  this.$router.go(0);
                //清空表单
              } else {
                this.$router.push({
                  path: '/integratedMana/servicePersonal',
                })
              }
            } catch (e) {
              console.log(e);
            }
          }
        });

      },
      async cascadeSelect(reloadMethod, key, v) {
        if (!v) {
          return;
        }
        this.pendingFlags[key] = true;
        try {
          const { list } = await umsService[reloadMethod](v);
          this.dics[key] = list;
        } catch (e) {
          console.log(e);
        }
        this.pendingFlags[key] = false;

      },
      async addTrain() {
        try {
          this.trainForm.trainingAssessmentTime = this.trainForm.trainingAssessmentTime.getTime();
          const trainData = await cscService[this.trainForm.id ? 'updateTrain' : 'addTrain'](this.trainForm);
          trainData.trainingAssessmentTime = new Date(trainData.trainingAssessmentTime);
          console.log(trainData);
          if (this.trainForm.id === 0) {
            this.trainList.push(trainData);
          } else {
            this.trainList.splice(this.trainList.findIndex(t=>t.id===this.trainForm.id),1,trainData);
          }
          this.resetTrainForm();
        } catch (e) {
          console.log(e);
        }
      },
      editTrain(row) {
        this.trainFormVisible = true;
        this.$nextTick(() => {
          this.trainForm = cloneDeep(row);
        });
      },
      resetTrainForm() {
        this.trainFormVisible = false;
        this.trainForm = {
          id: 0,
          workerId: 0,
          post: null,
          basicKnowledgeScore: 0,
          workSkillScore: 0,
          practicalOperationScore: 0,
          trainingAssessmentTime: null,
        };
      },
      async deleteTrain(id) {
        try {
          await cscService.deleteTrain(id);
          this.trainList = this.trainList.filter(t => t.id !== id);
        } catch (e) {
          console.log(e);
        }
      },
      trans4display(row, { property }) {
        if (property.endsWith('Time')) {
              let time = row[property];

              if(!time) {
                  return false;
              }
              if(/^[0-9]*$/.test(time))
                  return format(time, 'YYYY-MM-DD');
              else
                  return format(time.getTime(), 'YYYY-MM-DD');
        }
        switch (property) {
          case 'post':
            return this.post.find(p => p.id === row[property]).text;
            break;
          default:
            return '/';
        }
      },
      getFileListByType(t) {
        return this.vmData.picList.filter(({ type }) => (type === t)).map(({ picUrl: url }) => ({ url }));
      },
      total () {
          this.$http.get(`${MP}/worker/updateMoney?workerId=${this.trainForm.workerId}`).then(res => {
              if (res.data.errCode === 0) {
                  this.tWorkerPositionVo.variableAmount = 0
              } else {
                  alert(res.data.errMessage)
              }
          })
      },
      serverOrder () {
         this.$router.replace(`/integratedMana/worker/${this.submitData.worker.id}/orderList`)
      },
      map () {
        //    ${this.trainForm.workerId}
        this.mapFlag = !this.mapFlag
        this.$http.get(`${MP}/worker/getPosition?workerId=${this.trainForm.workerId}`).then(res => {
            let data = res.data
            if (!data.list.location) {
                this.mapFlag = !this.mapFlag
                alert('当前服务人员账号尚未进行接单，地图位置暂无。')
                return
            }
            this.drowMap(data.list.location, data.list.shelfType, data.list.workerName)
        })
      },
      async _getInit() {
        const { worker, picList, familyRelationList, cateList, trainList, tWorkerPositionVo } = await cscService.getServicePersonById(this.trainForm.workerId);
        Object.keys(this.vmData).forEach(key => {
        let exist = worker[key];
        if (exist) {
            this.vmData[key] = worker[key];
        }
        });
        if (familyRelationList.length) {
        this.vmData.familyRelationList = familyRelationList;
        }
        this.vmData.cateList = cateList.map(c => c.cateId);
        this.vmData.picList = picList;
        this.trainList = trainList.map(train => {
        Object.keys(train).forEach(key => {
            if (key.endsWith('Time')) {
            train[key] = new Date(train[key]);
            }
        });
        return train;
        });
        this.displayServiceArea = worker.provinceName + worker.cityName + worker.districtName + worker.streetName;
        this.tWorkerPositionVo = tWorkerPositionVo
      },
      drowMap(position, type, name) {
        let color = Object.is(type, 2) ? require('./green.png') : require('./red.png')
        let center = position.split(',')
        let mapData = []
        mapData.push(position)
        this.mapTotalNum = mapData.length  // 总数量
        const that = this
        let map = new AMap.Map('allmap', {
            mapStyle: 'amap://styles/1ab052905a9986ae39311b0425893e99', //样式URL
            resizeEnable: true,
            zoom: 14,
            center
        });
        var marker = new AMap.Marker({
            position: center,
            icon: new AMap.Icon({
                size: new AMap.Size(40, 50),
                image: color
            }),
            imageOffset: new AMap.Pixel(0, -60)
        })
        marker.setTitle(name)
        marker.setMap(map)
      },
      pageChange(page) {
        this.currentPage = page
        this._getList()
      },
      ...mapMutations(['SET_Provinces'])
    },
    computed: {
      submitData() {
        if (this.vmData.area) {
          const { provinceId, cityId, zoneId, streetId } = this.vmData.area;
          this.vmData.provinceId = Number(provinceId);
          this.vmData.cityId = Number(cityId);
          this.vmData.streetId = Number(streetId);
          this.vmData.districtId = Number(zoneId);
        }

        const worker = JSON.parse(JSON.stringify(this.vmData));
        if (this.isAdd) {
          worker.address = this.provinces.find(({ id }) => id === worker.provinceTmp).name +
            this.dics.cities.find(({ id }) => id === worker.cityTmp).name + this.dics.districts.find(({ id }) => id === worker.districtTmp).name + worker.address;
        }
        const cateList = worker.cateList.map(cateId => {
          return this.dics.cates.find(c => c.cateId === cateId);
        });

        delete worker.familyRelationList;
        delete worker.picList;
        delete worker.cateList;
        delete worker.area;
        delete worker.provinceTmp;
        delete worker.cityTmp;
        delete worker.districtTmp;
        return {
          worker,
          familyRelationList: this.vmData.familyRelationList,
          picList: this.vmData.picList,
          cateList,
        }
      },
      isEdit() {
        return /\/edit/.test(this.$route.path);
      },
      isAdd() {
        return this.isEdit && Number(this.$route.params.id) === 0;
      },
      title () {
        return this.isAdd ? '添加服务人员' : this.isEdit ? '修改服务人员' : '服务人员详情';
      },
      hasMoreRole(){
        return !this.isEdit || (!this.isAdd && this.isOrg) || (!this.isEdit && !this.isPf);
      },
      ...mapState(['post']),
      ...mapGetters(['isOrg','isPf','isGover', 'post', 'provinces']),
    },
    watch: {
      ['vmData.idNo']() {
        let birthday = "";
        if (this.vmData.idNo) {
          if (this.vmData.idNo.length === 15) {
            birthday = "19" + this.vmData.idNo.substr(6, 6);
          } else if (this.vmData.idNo.length === 18) {
            birthday = this.vmData.idNo.substr(6, 8);
          }
          birthday = birthday.replace(/(.{4})(.{2})(.{2})/, "$1年$2月$3日");
        }
        this.vmData.birthday = birthday;
      }
    },
    components: {
      FormChunkLabel
    }
  }
</script>
<style lang="scss">
    .page-container{
        padding-top: 15px;
        position: relative;
    }

    .tab-row{
        border-bottom: 1px solid #d1dbe5;
    }
    .tab {
        bottom: -1px;
        position: relative;
        padding: 0 30px;
        border: 1px solid #d1dbe5;
        border-radius: 4px 4px 0 0;
        display: inline-block;
        line-height: 40px;
        font-size: 18px;
        color: #616d80;
        cursor: pointer;
        &.active{
            border-bottom-color: #fff;
        }
    }

    .page-content{
        border: 1px solid #d1dbe5;
        border-top: 0;
        position: relative;
    }

    .back-btn{
        margin: 28px 0 28px 42px;
        color: #616d80;
    }
    .picture-label {
        color: #616d80;
        font-size: 18px;
        margin-bottom: 36px;
    }

    .picture-list {
        padding: 25px;
        border: 1px solid #DCDCDC;
    }

    .width80 {
        width: 80%;
    }

    .width100 {
        width: 100%;
    }

    .mt20px {
        margin-top: 20px;
    }

    .service_add {
        width: 1060px;
        h5 {
            width: 100%;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            border: 1px solid #ccc;
            font-size: 20px;
            height: 40px;
            padding-top: 5px;
            /*line-height: 30px;*/
            background-color: #f7f7f7;
            .el-button--small {
                margin-left: 20px;
            }

        }
        h6 {
            font-size: 20px;
        }
        .organization {
            margin-top: 20px;
            border-bottom: 1px solid #f0f0f0;
        }
        .base_info {
            margin-top: 20px;
            border-bottom: 1px solid #f0f0f0;
        }
        .picList {
            margin-top: 20px;
            border-bottom: 1px solid #f0f0f0;
        }
        .service_con {
            margin-top: 20px;
            border-bottom: 1px solid #f0f0f0;
        }
    }
    .map{
        position: absolute;
        top: 180px;
        left: 10px;
        right: 10px;
        bottom: 10px;
        border: 1px solid #00A6FC;
        z-index: 100;
    }
    #initInfo{
        height: 73px !important;
        display: flex;
        align-items: center;
        h4{
            display: flex;
            align-items: center;
            width: 150px !important;
            // height: 73px !important;
        }
    }
</style>
